const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🏗️ 简化版施工队伍数据初始化开始')
  console.log('📊 事件参数:', event)
  
  try {
    // 简化的施工队伍数据（只有3条用于测试）
    const constructionTeams = [
      {
        id: 'team_simple_001',
        name: '张师傅电气工程',
        type: 'individual',
        typeName: '个人师傅',
        category: 'electrical',
        categoryName: '电气工程',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200',
        experience: '15年',
        rating: 4.9,
        completedProjects: 156,
        location: '贵州省贵阳市',
        phone: '138****8888',
        specialties: ['强电安装', '弱电布线', '配电箱安装'],
        certifications: ['电工证', '高级电工证'],
        description: '从事电气工程15年，经验丰富，技术过硬。',
        priceRange: '200-500元/天',
        status: 'available',
        joinDate: '2023-03-15',
        tags: ['经验丰富', '技术过硬'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_simple_002',
        name: '华建装饰工程公司',
        type: 'company',
        typeName: '施工公司',
        category: 'decoration',
        categoryName: '装修装饰',
        avatar: 'https://images.unsplash.com/photo-1560472354-b33ff0c44a43?w=200',
        experience: '8年',
        rating: 4.8,
        completedProjects: 89,
        location: '贵州省遵义市',
        phone: '400-123-4567',
        specialties: ['室内装修', '办公装修', '商业装修'],
        certifications: ['建筑装修装饰工程专业承包资质'],
        description: '专业装修装饰公司，拥有专业设计团队。',
        priceRange: '面议',
        status: 'available',
        joinDate: '2022-08-20',
        tags: ['专业团队', '设计施工一体'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_simple_003',
        name: '李师傅水暖维修',
        type: 'individual',
        typeName: '个人师傅',
        category: 'plumbing',
        categoryName: '水暖工程',
        avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200',
        experience: '12年',
        rating: 4.7,
        completedProjects: 203,
        location: '贵州省六盘水市',
        phone: '139****9999',
        specialties: ['管道安装', '卫浴安装', '暖气维修'],
        certifications: ['管道工证', '防水工证'],
        description: '专业水暖师傅，技术娴熟，24小时服务。',
        priceRange: '150-400元/天',
        status: 'available',
        joinDate: '2023-01-10',
        tags: ['24小时服务', '技术娴熟'],
        createTime: new Date(),
        updateTime: new Date()
      }
    ]

    console.log('📊 准备插入数据条数:', constructionTeams.length)

    // 测试数据库连接
    console.log('🔗 测试数据库连接...')
    const testQuery = await db.collection('construction_teams').limit(1).get()
    console.log('✅ 数据库连接成功，当前数据条数:', testQuery.data.length)

    // 清空现有数据
    console.log('🗑️ 清空现有数据...')
    const removeResult = await db.collection('construction_teams').where({}).remove()
    console.log('🗑️ 删除完成，删除条数:', removeResult.stats.removed)

    // 逐条插入数据
    const results = []
    for (let i = 0; i < constructionTeams.length; i++) {
      const team = constructionTeams[i]
      console.log(`📦 插入第 ${i + 1} 条数据: ${team.name}`)
      
      try {
        const insertResult = await db.collection('construction_teams').add({
          data: team
        })
        results.push(insertResult)
        console.log(`✅ 第 ${i + 1} 条数据插入成功，ID: ${insertResult._id}`)
      } catch (insertError) {
        console.error(`❌ 第 ${i + 1} 条数据插入失败:`, insertError)
        throw insertError
      }
    }

    // 验证插入结果
    console.log('🔍 验证插入结果...')
    const verifyResult = await db.collection('construction_teams').get()
    console.log('✅ 验证完成，数据库中共有:', verifyResult.data.length, '条数据')

    console.log('✅ 简化版施工队伍数据初始化完成')
    
    return {
      success: true,
      message: '简化版施工队伍数据初始化成功',
      data: {
        totalCount: constructionTeams.length,
        insertedCount: results.length,
        verifiedCount: verifyResult.data.length,
        results: results.map(r => ({ _id: r._id }))
      }
    }

  } catch (error) {
    console.error('❌ 简化版施工队伍数据初始化失败:', error)
    return {
      success: false,
      error: error.message,
      stack: error.stack
    }
  }
}
